"""
"""

from cassandra.cluster import Cluster
from cassandra import ConsistencyLevel
from cassandra.query import BatchStatement, BatchType
import os
import sys
import json

class CassandraSession():
    """
    Description: Cassandra session operation encapsulation.
    """
    cluster = None
    session = None
    def __init__(self, cass_info, keyspace):
        """
        Description: Cassandra connection initialize.

        Parameters:
            cass_info:  Cassandra connection information (ipaddr, port, protocol_ver).
            keyspace:   The keyspace of the Cassandra.

        Returns:
            None
        """
        self.cluster = Cluster(protocol_version=4)
        self.session = self.cluster.connect()
        self.session.set_keyspace(keyspace)

    def __exit__(self):
        """
        Description: Cassandra connection uninitialize.

        Parameters:
            None.

        Returns:
            None
        """
        if self.session is not None:
            self.session.shutdown()
        if self.cluster is not None
            self.session.shutdown()

    def execute(self, cql_cmd):
        """
        Description: Cassandra CQL command execution.

        Parameters:
            cql_cmd: Command of CQL.

        Returns:
            Successful: Object of ResultSet.
            Failure:    None.
        """
        res = None
        if self.session is not None:
            res = self.session.execute(cql_cmd)

        return res

def move_cassandra_data(src_cass=None, dst_cass=None):
    """
    Description: Move Cassandra data from source node to other node.

    Parameters:
        src_cass:   Source Cassandra node connect information (ipaddr, port, protocol_ver).
        dst_cass:   Destination Cassandra node connect information (ipaddr, port, protocol_ver).

    Returns:
        Successful: True.
        Failure:    Falses.
    """
    ret = False
    return ret

def create_wmcloud_keyspace_table(src_cass=None):
    """
    Destination: Create Cassandra keyspace and table.

    Parameters:
        src_cass:   Source Cassandra node connect information (ipaddr, port, protocol_ver).

    Returns:
        Successful: True.
        Failure:    Falses.
    """
    ret = False
    cs = CassandraSession(src_cass)
    cs.execute(''' IF NOT EXISTS KEYSPACE wmcloud CREATE KEYSPACE wmcloud WITH replication = {'class': 'SimpleStrategy', \
                        'replication_factor': '1'}  AND durable_writes = true;''')
    cs.execute(''' IF NOT EXISTS TABLE wmcloud.foundation CREATE TABLE wmcloud.foundation_daily_transanction_info (
                        ticker text,
                        tradedate timestamp,
                        circulationshares double,
                        exchangecd text,
                        secshortname text,
                        secid text,
                        chg double,
                        chgpct double,
                        closeprice double,
                        discount double,
                        discountratio double,
                        highestprice double,
                        lowestprice double,
                        openprice double,
                        precloseprice double,
                        turnovervalue double,
                        turnovervol double,
                        PRIMARY KEY (ticker, tradedate, circulationshares, exchangecd, secshortname, secid)
                    ) WITH CLUSTERING ORDER BY (tradedate ASC, circulationshares ASC, exchangecd ASC, secshortname ASC, secid ASC)
                        AND bloom_filter_fp_chance = 0.01
                        AND caching = '{"keys":"ALL", "rows_per_partition":"NONE"}'
                        AND comment = ''
                        AND compaction = {'class': 'org.apache.cassandra.db.compaction.SizeTieredCompactionStrategy'}
                        AND compression = {'sstable_compression': 'org.apache.cassandra.io.compress.LZ4Compressor'}
                        AND dclocal_read_repair_chance = 0.1
                        AND default_time_to_live = 0
                        AND gc_grace_seconds = 864000
                        AND max_index_interval = 2048
                        AND memtable_flush_period_in_ms = 0
                        AND min_index_interval = 128
                        AND read_repair_chance = 0.0
                        AND speculative_retry = '99.0PERCENTILE'; ''')
    cs.execute(''' IF NOT EXISTS TABLE wmcloud.sz_sh_stock_basic_info CREATE TABLE wmcloud.sz_sh_stock_basic_info (
                        ticker text,
                        listdate timestamp,
                        delistdate timestamp,
                        enddate timestamp,
                        totalshares double,
                        equtype text,
                        equtypecd text,
                        exchangecd text,
                        excountrycd text,
                        listsector text,
                        listsectorcd int,
                        liststatuscd text,
                        nonrestfloata double,
                        nonrestfloatshares double,
                        officeaddr text,
                        partyid bigint,
                        primeoperating text,
                        secfullname text,
                        secid text,
                        secshortname text,
                        transcurrcd text,
                        tshequity double,
                        PRIMARY KEY (ticker, listdate, delistdate, enddate, totalshares)
                    ) WITH CLUSTERING ORDER BY (listdate ASC, delistdate ASC, enddate ASC, totalshares ASC)
                        AND bloom_filter_fp_chance = 0.01
                        AND caching = '{"keys":"ALL", "rows_per_partition":"NONE"}'
                        AND comment = ''
                        AND compaction = {'class': 'org.apache.cassandra.db.compaction.SizeTieredCompactionStrategy'}
                        AND compression = {'sstable_compression': 'org.apache.cassandra.io.compress.LZ4Compressor'}
                        AND dclocal_read_repair_chance = 0.1
                        AND default_time_to_live = 0
                        AND gc_grace_seconds = 864000
                        AND max_index_interval = 2048
                        AND memtable_flush_period_in_ms = 0
                        AND min_index_interval = 128
                        AND read_repair_chance = 0.0
                        AND speculative_retry = '99.0PERCENTILE'; ''')
    cs.execute(''' IF NOT EXISTS TABLE wmcloud.forward_m_s_contract_daily_transaction_info CREATE TABLE wmcloud.forward_m_s_contract_daily_transaction_info (
                        contractobject text,
                        tradedate timestamp,
                        ticker text,
                        secid text,
                        secshortname text,
                        exchangecd text,
                        chg double,
                        chg1 double,
                        chgpct double,
                        closeprice double,
                        contractmark text,
                        highestprice double,
                        lowestprice double,
                        maincon int,
                        openint double,
                        openprice double,
                        precloseprice double,
                        presettleprice double,
                        secshortnameen text,
                        settleprice double,
                        smaincon int,
                        turnovervalue double,
                        turnovervol double,
                        PRIMARY KEY (contractobject, tradedate, ticker, secid, secshortname, exchangecd)
                    ) WITH CLUSTERING ORDER BY (tradedate ASC, ticker ASC, secid ASC, secshortname ASC, exchangecd ASC)
                        AND bloom_filter_fp_chance = 0.01
                        AND caching = '{"keys":"ALL", "rows_per_partition":"NONE"}'
                        AND comment = ''
                        AND compaction = {'class': 'org.apache.cassandra.db.compaction.SizeTieredCompactionStrategy'}
                        AND compression = {'sstable_compression': 'org.apache.cassandra.io.compress.LZ4Compressor'}
                        AND dclocal_read_repair_chance = 0.1
                        AND default_time_to_live = 0
                        AND gc_grace_seconds = 864000
                        AND max_index_interval = 2048
                        AND memtable_flush_period_in_ms = 0
                        AND min_index_interval = 128
                        AND read_repair_chance = 0.0
                        AND speculative_retry = '99.0PERCENTILE'; ''')
    cs.execute(''' IF NOT EXISTS TABLE wmcloud.forward_basic_info CREATE TABLE wmcloud.forward_basic_info (
                        ticker text,
                        listdate timestamp,
                        lasttradedate timestamp,
                        firstdelidate timestamp,
                        lastdelidate timestamp,
                        secid text,
                        secfullname text,
                        secshortname text,
                        exchangecd text,
                        contmultnum double,
                        contmultunit text,
                        contractobject text,
                        contractstatus text,
                        contracttype text,
                        delicomminum double,
                        delicommiunit text,
                        deligrade text,
                        delimethod text,
                        delimonth int,
                        delipricemethod text,
                        deliyear int,
                        limitdownnum double,
                        limitdownunit text,
                        limitupnum double,
                        limitupunit text,
                        listbasisprice double,
                        minchgpricenum double,
                        minchgpriceunit text,
                        priceunit text,
                        pricevaliddecimal int,
                        settpricemethod text,
                        tradecomminum double,
                        tradecommiunit text,
                        trademarginratio double,
                        transcurrcd text,
                        PRIMARY KEY (ticker, listdate, lasttradedate, firstdelidate, lastdelidate, secid, secfullname, secshortname, exchangecd)
                    ) WITH CLUSTERING ORDER BY (listdate ASC, lasttradedate ASC, firstdelidate ASC, lastdelidate ASC, secid ASC, secfullname ASC, secshortname ASC, exchangecd ASC)
                        AND bloom_filter_fp_chance = 0.01
                        AND caching = '{"keys":"ALL", "rows_per_partition":"NONE"}'
                        AND comment = ''
                        AND compaction = {'class': 'org.apache.cassandra.db.compaction.SizeTieredCompactionStrategy'}
                        AND compression = {'sstable_compression': 'org.apache.cassandra.io.compress.LZ4Compressor'}
                        AND dclocal_read_repair_chance = 0.1
                        AND default_time_to_live = 0
                        AND gc_grace_seconds = 864000
                        AND max_index_interval = 2048
                        AND memtable_flush_period_in_ms = 0
                        AND min_index_interval = 128
                        AND read_repair_chance = 0.0
                        AND speculative_retry = '99.0PERCENTILE'; ''')
    cs.execute(''' IF NOT EXISTS TABLE wmcloud.sz_sh_stock_daily_trade_info CREATE TABLE wmcloud.sz_sh_stock_daily_trade_info (
                        ticker text,
                        tradedate timestamp,
                        secid text,
                        secshortname text,
                        exchangecd text,
                        accumadjfactor double,
                        actprecloseprice double,
                        closeprice double,
                        dealamount int,
                        highestprice double,
                        lowestprice double,
                        marketvalue double,
                        negmarketvalue double,
                        openprice double,
                        precloseprice double,
                        turnoverrate double,
                        turnovervalue double,
                        turnovervol double,
                        PRIMARY KEY (ticker, tradedate, secid, secshortname, exchangecd)
                    ) WITH CLUSTERING ORDER BY (tradedate ASC, secid ASC, secshortname ASC, exchangecd ASC)
                        AND bloom_filter_fp_chance = 0.01
                        AND caching = '{"keys":"ALL", "rows_per_partition":"NONE"}'
                        AND comment = ''
                        AND compaction = {'class': 'org.apache.cassandra.db.compaction.SizeTieredCompactionStrategy'}
                        AND compression = {'sstable_compression': 'org.apache.cassandra.io.compress.LZ4Compressor'}
                        AND dclocal_read_repair_chance = 0.1
                        AND default_time_to_live = 0
                        AND gc_grace_seconds = 864000
                        AND max_index_interval = 2048
                        AND memtable_flush_period_in_ms = 0
                        AND min_index_interval = 128
                        AND read_repair_chance = 0.0
                        AND speculative_retry = '99.0PERCENTILE'; ''')
    cs.execute(''' IF NOT EXISTS TABLE wmcloud.foundation_basic_info CREATE TABLE wmcloud.foundation_basic_info (
                        ticker text,
                        establishdate timestamp,
                        circulationshares double,
                        liststatuscd text,
                        listdate timestamp,
                        delistdate timestamp,
                        category text,
                        operationmode text,
                        indexfund text,
                        etflof text,
                        custodian bigint,
                        custodianfullname text,
                        exchangecd text,
                        guarperiod double,
                        guarratio double,
                        investfield text,
                        investtarget text,
                        isclass int,
                        isfof boolean,
                        isguarfund boolean,
                        isqdii boolean,
                        managementcompany bigint,
                        managementfullname text,
                        managername text,
                        perfbenchmark text,
                        secid text,
                        secshortname text,
                        tradeabbrname text,
                        PRIMARY KEY (ticker, establishdate, circulationshares, liststatuscd, listdate, delistdate, category, operationmode, indexfund, etflof)
                    ) WITH CLUSTERING ORDER BY (establishdate ASC, circulationshares ASC, liststatuscd ASC, listdate ASC, delistdate ASC, category ASC, operationmode ASC, indexfund ASC, etflof ASC)
                        AND bloom_filter_fp_chance = 0.01
                        AND caching = '{"keys":"ALL", "rows_per_partition":"NONE"}'
                        AND comment = ''
                        AND compaction = {'class': 'org.apache.cassandra.db.compaction.SizeTieredCompactionStrategy'}
                        AND compression = {'sstable_compression': 'org.apache.cassandra.io.compress.LZ4Compressor'}
                        AND dclocal_read_repair_chance = 0.1
                        AND default_time_to_live = 0
                        AND gc_grace_seconds = 864000
                        AND max_index_interval = 2048
                        AND memtable_flush_period_in_ms = 0
                        AND min_index_interval = 128
                        AND read_repair_chance = 0.0
                        AND speculative_retry = '99.0PERCENTILE'; ''')
    return ret

if __name__ == '__main__':
    # create keyspace and table on new cluster
    src_cass = ('', 0, 4)
    dst_cass = ('', 0, 4)
    create_wmcloud_keyspace_table(src_cass)
    # move data from old node to new cluster
    move_cassandra_data(src_cass, dst_cass)
